package com.escom.healthlc.controller;

import com.escom.healthlc.business.LoginBusiness;
import com.escom.healthlc.entidad.MedicoVO;
import com.escom.healthlc.entidad.UsuarioVO;
import com.escom.healthlc.utils.Constantes;
import java.io.IOException;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Carlos
 */
@ManagedBean(name = "LoginController")
@ViewScoped
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    private UsuarioVO usuarioCreate;

    @ManagedProperty("#{LoginBusiness}")
    private LoginBusiness loginBusiness;

    public LoginController() {
    }

    @PostConstruct
    private void initLoginController() {
        usuarioCreate = new UsuarioVO();
    }

    public void executeIniciarSesion(ActionEvent acEvt) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        FacesMessage facesMessage;
        loginBusiness.validarSesion(usuarioCreate);
        int estado = loginBusiness.getEstado();
        String messageEstado = loginBusiness.getMessageEstado();
        switch (estado) {
            case Constantes.ERROR_BASE_DATOS:
                facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constantes.MESSAGE_TITLE, messageEstado);
                facesContext.addMessage(null, facesMessage);
                break;
        }
        boolean successSession = loginBusiness.isSuccessSession();
        if (successSession) {
            ExternalContext externalContext = facesContext.getExternalContext();
            HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
            String contextPath = ((ServletContext) externalContext.getContext()).getContextPath();
            HttpSession httpSession = request.getSession(true);
            UsuarioVO usuarioBD = loginBusiness.obtenerUsuarioByNickPass(usuarioCreate);
            String tipoUsuario = usuarioBD.getTipoUsuario();
            tipoUsuario = (tipoUsuario == null) ? "" : tipoUsuario;
            MedicoVO medicoActivio;
            switch (tipoUsuario) {
                case "medico":
                    medicoActivio = loginBusiness.obtenerMedicoByUsuario(usuarioCreate);
                    httpSession.setAttribute("usuarioActivio", medicoActivio);
                    try {
                        externalContext.redirect(contextPath + "/view/index-med.jsf");
                    } catch (IOException ex) {
                        logger.error("Logger Error: {}", ex.getCause().getMessage());
                        logger.error("Logger Error: {}", ex.fillInStackTrace().toString());
                    }
                    break;
                case "paciente":
                    try {
                        externalContext.redirect(contextPath + "/view/indexSimple.jsf");
                    } catch (IOException ex) {
                        logger.error("Logger Error: {}", ex.getCause().getMessage());
                        logger.error("Logger Error: {}", ex.fillInStackTrace().toString());
                    }
                    break;
                case "admin":
                    medicoActivio = loginBusiness.obtenerMedicoByUsuario(usuarioCreate);
                    httpSession.setAttribute("usuarioActivio", medicoActivio);
                    try {
                        externalContext.redirect(contextPath + "/view/index-adm.jsf");
                    } catch (IOException ex) {
                        logger.error("Logger Error: {}", ex.getCause().getMessage());
                        logger.error("Logger Error: {}", ex.fillInStackTrace().toString());
                    }
                    break;
            }
        } else {
            facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, Constantes.MESSAGE_TITLE, "El usuario/contraseña es incorrecta");
            facesContext.addMessage(null, facesMessage);
        }
    }

    public void executeCerrarSesion(ActionEvent acEvt) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
//        externalContext.invalidateSession();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession httpSession = request.getSession(true);
        httpSession.invalidate();
    }

    public void limpiarObjects(ActionEvent acEvt) {
        usuarioCreate = new UsuarioVO();
    }

    public UsuarioVO getUsuarioCreate() {
        return usuarioCreate;
    }

    public void setUsuarioCreate(UsuarioVO usuarioCreate) {
        this.usuarioCreate = usuarioCreate;
    }

    public void setLoginBusiness(LoginBusiness loginBusiness) {
        this.loginBusiness = loginBusiness;
    }

}
